"use client";

import React, { useEffect, useState } from "react";

function Field({ label, type = "text", value, onChange, name }) {
  return (
    <label className="block mb-3">
      <span className="block text-sm text-gray-700 mb-1">{label}</span>
      <input
        className="w-full border rounded px-3 py-2"
        type={type}
        value={value}
        name={name}
        onChange={(e) => onChange(e.target.value)}
      />
    </label>
  );
}

export default function AccountContent({ dict, lang }) {
  const [mode, setMode] = useState("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [displayName, setDisplayName] = useState("");
  const [user, setUser] = useState(null);
  const [msg, setMsg] = useState("");

  async function refreshMe() {
    const res = await fetch(`/${lang}/api/auth/me`, { cache: "no-store" });
    const data = await res.json();
    setUser(data.user);
  }

  useEffect(() => {
    refreshMe();
  }, []);

  async function submit(e) {
    e.preventDefault();
    setMsg("");
    const endpoint = mode === "login" ? "login" : "register";
    const payload = mode === "login" ? { email, password } : { email, password, displayName };
    const res = await fetch(`/${lang}/api/auth/${endpoint}`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(payload),
    });
    const data = await res.json();
    if (!res.ok) {
      const errorMsg = data.detail ? `${data.error}: ${data.detail}` : (data.error || dict.account_failed);
      setMsg(errorMsg);
    } else {
      setMsg(dict.account_success);
      setEmail("");
      setPassword("");
      setDisplayName("");
      await refreshMe();
    }
  }

  async function logout() {
    await fetch(`/${lang}/api/auth/logout`, { method: "POST" });
    await refreshMe();
  }

  return (
    <div className="max-w-md mx-auto mt-8">
      <h1 className="text-2xl font-bold mb-4">{dict.account_title}</h1>
      {user ? (
        <div className="bg-white rounded shadow p-4">
          <p className="mb-2">{dict.account_signed_in_as}: <strong>{user.email}</strong></p>
          {user.display_name && <p className="mb-4">{dict.account_name}: {user.display_name}</p>}
          <button className="bg-gray-700 text-white px-4 py-2 rounded" onClick={logout}>
            {dict.account_logout}
          </button>
        </div>
      ) : (
        <div className="bg-white rounded shadow p-4">
          <div className="mb-4">
            <button
              className={`px-3 py-1 rounded mr-2 ${mode === "login" ? "bg-blue-700 text-white" : "bg-gray-200"}`}
              onClick={() => setMode("login")}
            >
              {dict.account_login}
            </button>
            <button
              className={`px-3 py-1 rounded ${mode === "register" ? "bg-blue-700 text-white" : "bg-gray-200"}`}
              onClick={() => setMode("register")}
            >
              {dict.account_register}
            </button>
          </div>
          <form onSubmit={submit}>
            <Field label={dict.account_email} value={email} onChange={setEmail} name="email" />
            <Field label={dict.account_password} type="password" value={password} onChange={setPassword} name="password" />
            {mode === "register" && (
              <Field label={dict.account_display_name} value={displayName} onChange={setDisplayName} name="displayName" />
            )}
            <button className="bg-blue-700 text-white px-4 py-2 rounded" type="submit">
              {mode === "login" ? dict.account_login : dict.account_register}
            </button>
          </form>
          {msg && <p className="mt-3 text-sm text-red-600">{msg}</p>}
        </div>
      )}
    </div>
  );
}

